-module(queue_service).
-include("rec_dec.hrl").
-include_lib("stdlib/include/qlc.hrl").
-export([start/0,addchange/1,get/0,del/1,get/1,delete/1]).
-define(TAB    , queue_rec).

start() ->
	case db_mgr:check_table(?TAB) of
	no_found ->
		db_mgr:create_table(?TAB,record_info(fields,?TAB));
	_ ->
		ok
	end.

addchange(Rec) ->
	case Rec#?TAB.id of
	<<"">> ->
		add(Rec);
	"" ->
		add(Rec);
	_ ->
		modify(Rec)
	end.

add(Rec) when is_record(Rec,?TAB) ->
	Id = gen_server:call(couch_uuids,create),
	db_mgr:write(?TAB,Rec#?TAB{id=Id}).
	

modify(Rec) when is_record(Rec,?TAB) ->
	db_mgr:write(?TAB,Rec).

delete(Id) ->
	del(Id).
	
del(ID) -> 
	db_mgr:del(?TAB,ID).

	
get() -> %% get all vendor info
	db_mgr:get(?TAB).
	
get({vendor_id,Id}) ->
	Qry = qlc:q([X||X <- mnesia:table(?TAB),X#?TAB.vendor_id =:= Id]),
	db_mgr:do_transaction(fun() -> qlc:e(Qry) end);

get({vendor_id,Id,Num}) ->
	Qry = qlc:q([X||X <- mnesia:table(?TAB),X#?TAB.vendor_id =:= Id]),
	db_mgr:do_transaction(fun() -> qlc:e(Qry,[{max_list_size,Num}]) end);


get({id,Id}) ->
	db_mgr:get(?TAB,Id).
    
    